package com.polaris.live.manager

import android.app.Activity
import android.util.Log
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.Utils
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.ServerConfig
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.manager.withRetryNow
import com.polaris.live.common.network.getSuccessResult
import com.polaris.live.common.resp.DoMainResp
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.net.userService
import com.polaris.live.resp.event.IpCountryInitializedEvent
import com.polaris.live.resp.go_resp.QuickLoginBean
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

/**
 * DomainManager
 *
 * @author Created by lucas on 2023/10/26 10:42
 */
object DomainManager {

    init {
        //监听前后台状态
        AppUtils.registerAppStatusChangedListener(object : Utils.OnAppStatusChangedListener {
            override fun onForeground(activity: Activity?) {
                if (UserManager.isLogin()) {
                    quickLoginWithAsync()
                }
            }

            override fun onBackground(activity: Activity?) {}
        })
    }

    /**
     * 异步调用
     */
    fun quickLoginWithAsync() {
        CoroutineScopeManager.ioScope.launch {
            quickLogin()
        }
    }

    /**
     * 快速登录
     *
     * 成功登录后在前后台切换时需要调用
     */
    private suspend fun quickLogin() {
        if (!UserManager.isLogin()) {
            return
        }

        val userResp = userService.quickLogin(QuickLoginBean()).getSuccessResult()
        if (userResp != null) {
            UserManager.setUser(userResp)
        }
    }

    /**
     * 异步处理domain机制
     */
    fun domainWithAsync() {
        CoroutineScopeManager.defaultScope.launch {
            fetchMainUrl()
        }
    }

    /**
     * domain请求，用于获取主域名
     */
    suspend fun fetchMainUrl(): String? {
        val lastDomainUrls = AppConst.domainUrls
        if (lastDomainUrls.isEmpty()) {
            return null
        }

        for (domainUrl in lastDomainUrls) {
            try {
                val newUrl =
                    resolveUrl(domainUrl) + "platformType=${AppConst.PLATFORM_TYPE}&appType=${AppConst.APP_TYPE}&country=${AppModule.getLanguageCountry()}"

                val res = DownloadManager.downloadSimple(newUrl)
                val resp = JsonUtils.fromJson<DoMainResp>(res)
                val domainAddresses = resp?.domainAddresses
                val mainBaseUrl = resp?.mainBaseUrl
                if (!domainAddresses.isNullOrEmpty() && !mainBaseUrl.isNullOrEmpty()) {
                    //如果不为空则覆盖本地配置
                    CacheUtil.saveDomainUrls(domainAddresses)
                    CacheUtil.saveMainUrl(mainBaseUrl)

                    //这里只修改domain的地址
                    ServerConfig.updateCustomConfig(null, domainAddresses)

                    return mainBaseUrl
                }
            } catch (t: Throwable) {
                Log.e("--net", "domain", t)
            }
        }

        return null
    }

    private fun resolveUrl(url: String): String {
        return url.dropLastWhile { it == '?' || it == '/' } + "/domain?"
    }

    fun asyncFetchIpCountry(uniqueId: String) {
        CoroutineScopeManager.defaultScope.launch {
            fetchIpCountry(true, uniqueId)
        }
    }

    //获取ip国家
    suspend fun fetchIpCountry(forceFetch: Boolean = false, uniqueId: String? = null): String? {
        if (!forceFetch) {
            val lastIpCountry = CommonCache.getIpCountry()
            if (lastIpCountry != null) {
                return lastIpCountry
            }
        }

        return try {
            val finalUniqueId = uniqueId ?: AppModule.getUniqueDeviceId()
            if (finalUniqueId == null) {
                null
            } else {
                val resp = withRetryNow { userService.getIp(finalUniqueId) }

                resp.result?.country?.also {
                    CommonCache.setIpCountry(it)

                    EventBus.getDefault().post(IpCountryInitializedEvent(it))
                }
            }
        } catch (_: Throwable) {
            null
        }
    }
}